package com.yun.zf.app.mqListener;

import cn.hutool.core.date.DateUtil;
import com.yun.zf.common.app.domain.SysCoupon;
import com.yun.zf.common.app.domain.SysCouponReceive;
import com.yun.zf.common.app.domain.ZfInvite;
import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.system.service.ISysUserService;
import com.yun.zf.system.service.SysCouponReceiveService;
import com.yun.zf.system.service.SysCouponService;
import com.yun.zf.system.service.ZfInviteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "${rocketmq.producer.groupName}",topic = "new_user")
public class UserListener implements RocketMQListener<Map<String,String>> {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ZfInviteService inviteService;
    @Autowired
    private SysCouponService couponService;
    @Autowired
    private SysCouponReceiveService couponReceiveService;
    @Override
    public void onMessage(Map<String,String> map) {
        String inviteId = map.get("inviteId");
        String invitedId = map.get("invitedId");
        // 生成邀请记录
        if (StringUtils.isNotBlank(inviteId)){
            int count=  userService.getUserCountById(Long.parseLong(inviteId));
            if (count>0){
                ZfInvite invite = new ZfInvite();
                invite.setInvitedId(Long.parseLong(invitedId));
                invite.setInviteId(Long.parseLong(inviteId));
                inviteService.addInvite(invite);
            }
        }
        //发放新人优惠券
       SysCoupon couponList = couponService.getCouponByType(1);
        if (couponList!=null){
            SysCouponReceive couponReceive = new SysCouponReceive();
            couponReceive.setUserId(Long.parseLong(invitedId));
            couponReceive.setCouponId(couponList.getId());
            couponReceive.setUserStatus(1);
            couponReceive.setRStartTime(new Date());
            couponReceive.setCreateTime(new Date());
            couponReceive.setREndTime(DateUtil.offsetDay(new Date(),couponList.getLimitDay()) );
            couponReceiveService.receiveCoupon(couponReceive);
        }

    }
}
